package com.ly.web;

import com.github.pagehelper.PageInfo;
import com.ly.annotation.RoleRequire;
import com.ly.mapper.ExamMapper;
import com.ly.po.CoursesPO;
import com.ly.po.ExamCoursePO;
import com.ly.po.ExamPO;
import com.ly.pojo.Courses;
import com.ly.pojo.Exam;
import com.ly.query.ExamQuery;
import com.ly.result.R;
import com.ly.service.CourseService;
import com.ly.service.ExamService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/exam")
public class ExamController {

    @Autowired
    private ExamService examService;

    @Autowired
    private ExamMapper examMapper;

    @Autowired
    private CourseService courseService;

    /**
     * 根据课程id去获取考试安排数据PO
     */
    @GetMapping("/exam/course/{courseId}")
    @RoleRequire("TEACHER")
    public R getExamPO(@PathVariable int courseId) {

        ExamPO examPO = examService.getExamPOByCourseId(courseId);
        if (examPO != null){
            return R.success(examPO);
        } else {
            return R.error("获取失败");
        }
    }

    /**
     * 根据课程代码去查询对应课程的考试安排，如果没有则返回空
     */
    @GetMapping("/exam/info")
    @RoleRequire("ADMIN")
    public R getExamInfoByCourseCode(@RequestParam("courseCode") String courseCode) {
        Exam exam = examService.getExamByCourseCode(courseCode);
        if (exam != null) {
            return R.success(exam);
        }
        return R.success(null);
    }

    /**
     * 获得全部的考试安排数据（PO）（教师相关）
     */
    @GetMapping("/exam/course/tno/{tno}")
    @RoleRequire("TEACHER")
    public R getAllExamPO(@RequestParam int page, @RequestParam int size, @PathVariable Long tno) {
        List<Courses> coursesList = courseService.getCourseListByTno(tno);
        PageInfo<ExamPO> pageInfo = examService.getAllExamByCourseList(page, size, coursesList);
        return R.success(pageInfo.getList(), String.valueOf(pageInfo.getTotal()));
    }

    /**
     * 获得指定学生对应的全部的考试安排数据（PO）
     */
    @GetMapping("/exam/{sno}")
    @RoleRequire("STUDENT")
    public R getAllExamPOByStudent(@PathVariable Long sno, @RequestParam int page, @RequestParam int size) {
        PageInfo<ExamPO> pageInfo = examService.getAllExamByStudent(sno, page, size);
        return R.success(pageInfo.getList(), String.valueOf(pageInfo.getTotal()));
    }

    /**
     * 新增考试安排
     * @param exam
     * @return
     */
    @PostMapping("/exam")
    @RoleRequire("ADMIN")
    public R saveExam(@RequestBody Exam exam) {
        int i = examService.insertExam(exam);
        if (i == 1) {
            return R.success("保存成功");
        } else {
            return R.error("保存失败");
        }
    }

    /**
     * 根据课程代码取消考试安排
     */
    @DeleteMapping("/exam/{courseCode}")
    @RoleRequire("ADMIN")
    public R deleteExam(@PathVariable String courseCode) {
        int i = examService.deleteExamByCourseCode(courseCode);
        if (i == 1) {
            return R.success("删除成功");
        } else {
            return R.error("删除失败");
        }
    }

    /**
     * 修改考试安排
     * @param examPO
     * @return
     */
    @PutMapping("/exam")
    @RoleRequire("TEACHER")
    public R updateExam(@RequestBody ExamPO examPO) {
        int i = examService.updateExam(examPO);
        if (i == 1) {
            return R.success("保存成功");
        } else {
            return R.error("保存失败");
        }
    }

    /**
     * 删除指定考试安排
     */
    @DeleteMapping("/exam/{courseId}/{tno}")
    @RoleRequire("TEACHER")
    public R deleteExam(@PathVariable int courseId, @PathVariable Long tno) {
        //先判断这个教师工号所教授的课程中是否包含该课程id，若不，直接返回错误
        int j = examService.containtCourse(courseId, tno);
        if (j == 1) {
            //包含
            return R.error("无权限");
        }
        int i = examService.deleteExamByCourseId(courseId);
        if (i == 1) {
            return R.success("删除成功");
        } else {
            return R.error("删除失败");
        }
    }

    /**
     * 获得所有的考试安排（支持分页和分类）
     */
    @GetMapping("/exam/all")
    @RoleRequire("ADMIN")
    public R getAllExam(
            @RequestParam(defaultValue = "1") int page,
            @RequestParam(defaultValue = "10") int size,
            @RequestParam(required = false) String college,
            @RequestParam(required = false) String major,
            @RequestParam(required = false) String classCode,
            @RequestParam(required = false) String semester
    ) {
        try {
            ExamQuery query = new ExamQuery(page,size,college,major,classCode,semester);

            Page<ExamCoursePO> examPage = examService.getAllExams(query);

            return R.success(examPage.getContent(), String.valueOf(examPage.getTotalElements()));

        } catch (Exception e) {
            R.error("查询失败：" + e.getMessage());
        }
        return R.error("查询失败");
    }

    @GetMapping("/exam/filter-options")
    public R getFilterOptions() {
        try {
            Map<String, Object> options = new HashMap<>();

            // 获取学院列表（去重）
            List<String> colleges = examMapper.selectDistinctColleges();
            options.put("colleges", colleges);

            // 获取专业列表（去重）
            List<String> majors = examMapper.selectDistinctMajors();
            options.put("majors", majors);

            // 获取学期列表（去重）
            List<String> semesters = examMapper.selectDistinctSemesters();
            options.put("semesters", semesters);

            System.out.println(colleges);
            System.out.println(majors);
            System.out.println(semesters);

            Map<String, Object> response = new HashMap<>();
            response.put("code", 200);
            response.put("data", options);

            return R.success(response);

        } catch (Exception e) {
            Map<String, Object> errorResponse = new HashMap<>();
            errorResponse.put("code", 500);
            errorResponse.put("message", "获取筛选选项失败: " + e.getMessage());
            return R.error("获取失败");
        }
    }

}
